package com.sinoglobal.dumping.activity;

import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.sinoglobal.dumping.base.Dumpling_SharedPreferenceUtil;
import com.sinoglobal.dumping.util.Dumpling_FileUtils;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import dalvik.system.DexClassLoader;

/**
 * Created by Administrator on 2016/3/4.
 */
public class ProxyActivity extends Activity {
    public static final String EXTRA_DEX_PATH = "extra.dex.path";
    public static final String EXTRA_URL = "extra.url";
    public static final String EXTRA_CLASS = "extra.class";
    private static final String TAG = ProxyActivity.class.getSimpleName();
    private static final String FROM = "extra.from";
    private static final int FROM_EXTERNAL = 0;
    private static final String RECEIVER_ACTION = "com.sino.host.PLUGIN_ACTION";
    private String mDexPath;
    private String mClass;
    private Uri resultImage;// = Uri.parse("http://www.baidu.com");
    public static String fileName = Dumpling_FileUtils.imageFileName;
    private Object instance;
    private Class<?> localClass;//Class<capture of ?>

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDexPath = getIntent().getStringExtra(EXTRA_DEX_PATH);
        String url = getIntent().getStringExtra(EXTRA_URL);
        resultImage = Uri.parse(url);
        mClass = getIntent().getStringExtra(EXTRA_CLASS);
        Log.d(TAG, "mDexPath=" + mDexPath + ",mClass=" + mClass);
        if (mClass==null){
            lunchTargetActivity();
        }else{
            lunchTargetActivity(mClass);
        }
    }

    protected void lunchTargetActivity(String className) {
        Log.d(TAG, "start lunchTargetActivity, class=" + className);
        File dexOutputDir = getDir("dex", 0);
        String dexOutputPath = dexOutputDir.getAbsolutePath();
        ClassLoader localClassLoader = ClassLoader.getSystemClassLoader();
        DexClassLoader dexClassLoader = new DexClassLoader(mDexPath,
                dexOutputPath, null, localClassLoader);
        try {
            localClass = dexClassLoader.loadClass(className);
            Constructor<?> localConstructor = localClass
                    .getConstructor(new Class[]{});
            instance = localConstructor.newInstance(new Object[]{});
            Log.d(TAG, "instance=" + instance);

            Method setProxy = localClass.getMethod("setProxy",
                    new Class[]{Activity.class});
            setProxy.setAccessible(true);
            Object result = setProxy.invoke(instance, new Object[]{this});
            Log.d(TAG, "result=" + result);

            Method oncreate = localClass.getDeclaredMethod("onCreate",
                    new Class[]{Bundle.class});
            oncreate.setAccessible(true);
            Bundle bundle = new Bundle();
            bundle.putInt(FROM, FROM_EXTERNAL);
            oncreate.invoke(instance, new Object[]{bundle});

        } catch (ClassNotFoundException e) {
            Log.e(TAG, "loadClass e:" + e);
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            Log.e(TAG, "getConstructor e:" + e);
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            Log.e(TAG, "newInstance e:" + e);
            e.printStackTrace();
        } catch (InstantiationException e) {
            Log.e(TAG, "newInstance e:" + e);
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            Log.e(TAG, "newInstance e:" + e);
            e.printStackTrace();
        }

    }

    protected void lunchTargetActivity() {
        PackageInfo packageInfo = getApplicationContext().getPackageManager()
                .getPackageArchiveInfo(mDexPath, PackageManager.GET_ACTIVITIES);
        Log.d(TAG, "packageInfo:" + packageInfo);
        if ((packageInfo.activities!=null) &&
                (packageInfo.activities.length>0)){
            String activityName = packageInfo.activities[0].name;
            mClass = activityName;
            lunchTargetActivity(mClass);
        }
    }


    private void uploadPic(){
        Log.e(TAG, "uploadPic url:"+resultImage+", fileName:"+fileName);
        try {
            Method upload = localClass.getMethod("upload", Uri.class, String.class);
            upload.setAccessible(true);
            upload.invoke(instance, resultImage, fileName);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void setTitle(CharSequence title) {
        super.setTitle(title);
        Log.e(TAG, "title:" + title);
        if (title.equals("initOk")){
            uploadPic();
        }else if (title.equals("initFaile")){
            Log.e(TAG, "CheckBucketExists init fail!");
            Toast.makeText(this, "云存储初始化失败，请稍后再试...", Toast.LENGTH_SHORT).show();
        }else if (title.equals("success")){
            //图片上传成功后标志设置为true
            Dumpling_SharedPreferenceUtil.put(this, "uploadFlag", true);
            //这里表示图片上传云存储成功
            //在这里执行saveCardInfo(Dumpling_FileUtils.imageFileName);该函数
            setResult(Dumpling_CongratulationCardActivity.UPLOAD_IMAGE_CODE);
            finish();
        }
    }
}
